# coding=utf-8
import requests
import re
import json

from src.common import log
from src.common.readConfig import ReadConfig
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.firefox.options import Options

from src.common.screenshot import *

sdd_login_readconfig = ReadConfig ("pre")


def click_sms():
    '''模拟点击短信验证码方法'''
    options = Options ()
    options.headless = True
    driver = webdriver.Firefox (options=options)  # options=options：无界面登录方法设置
    # driver = webdriver.Firefox ()  # 需要有界面显示使用
    driver.implicitly_wait (15)
    driver.get (sdd_login_readconfig.get_url ("sdd_url"))
    driver.maximize_window ()
    time.sleep (2)
    driver.find_element (By.ID, "userTel").click ()
    element = driver.find_element (By.ID, "userTel")
    actions = ActionChains (driver)
    actions.double_click (element).perform ()
    driver.execute_script ("window.scrollTo(0,0)")
    driver.find_element (By.ID, "userTel").send_keys (sdd_login_readconfig.get_body ("sdd_mobile"))
    driver.find_element (By.ID, "password").click ()
    driver.find_element (By.ID, "password").send_keys ("123456")
    driver.find_element (By.CSS_SELECTOR, ".ant-btn-link").click ()
    driver.find_element (By.ID, "verifyCode").click ()
    time.sleep (2)
    takeScreenshot (driver, createDir ("jyy"), "login")  # 调用截图方法截图执行后页面并保存执行结果页面
    log.logger_info.info ("----短信验证码点击完毕----")
    driver.close ()

# 商多多登录
def sdd_login():
    try:
        log.logger_info.info ("----开始链接商多多登录----")
        login_url = sdd_login_readconfig.get_url ("sdd_login_url")
        header = sdd_login_readconfig.get_body ("header")
        body_login = sdd_login_readconfig.get_body ("sdd_login_body")

        session = requests.Session ()
        click_sms ()
        # log.logger_info.info ("商多多验证码获取返回信息：" + str (result))
        r = session.post (login_url, json=body_login, headers=header)
        log.logger_info.info ("商多多登录返回信息：" + str (r.json ()))
        cookie_jar = r.cookies
        cookie = requests.utils.dict_from_cookiejar (cookie_jar)
        for cookie1 in cookie_jar:
            # 获取cookie的失效时间
            expiry_date = cookie1.expires
            # 转化为当前时间
            print (time.ctime (expiry_date))
        # 将cookie值以及cookie过期时间写入文件中
        data_file = open (r"../testfile/sdd_cookie.txt", "w")
        data_file.write (str (cookie))
        data_file.write ("\n" + str (expiry_date))
        log.logger_info.info ("----商多多登录成功----")
        return cookie
        data_file.close ()

    except Exception as ex:
        log.logger_error.error ("商多多登录失败:" + str (ex))


# 实际获取商多多cookie调用的方法
def sdd_login_data():
    if os.path.exists (r"../testfile/sdd_cookie.txt") is False:
        return sdd_login ()
    else:
        fd = open (r"../testfile/sdd_cookie.txt")
        # 把txt文件按列表形式读取出来
        fd_len = len (fd.read ())
        print (fd_len)
        if fd_len > 5:
            # 将指针归位
            fd.seek (0)
            data_txt = fd.readlines ()
            text = data_txt[0]
            # 把str类型的转换车dict类型，需要先把字符串的单引号转换成双引号
            cookie_text = json.loads (re.sub ('\'', '\"', text))
            expiry_date = int (data_txt[1])
            print (time.ctime (expiry_date))
            # 判断当前时间大于失效时间，重新获取cookie，否则继续使用原来的cookie
            if time.time () < expiry_date:
                fd.close ()
                log.logger_info.info ("本次商多多登录方式是获取cookie文件保存的cookie值")
                return cookie_text
            else:
                return sdd_login ()
        else:
            return sdd_login ()


if __name__ == '__main__':
    sdd_login ()
